package cn.tinkerpatch.com.tinker;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;

import java.io.File;

import cn.tinkerpatch.com.http.DisposeDataListener;
import cn.tinkerpatch.com.http.DisposeDownLoadListener;
import cn.tinkerpatch.com.http.RequestCenter;
import cn.tinkerpatch.com.tinker.module.BasePath;

/**
 * Created by admin
 * 2018/10/7.
 * content
 */

@SuppressWarnings("ResultOfMethodCallIgnored") public class TinkerService extends Service {
    private static final String FILE_END = ".apk";//文件后缀名
    private static final int DOWNLOAD_PATH = 1; //下载patch文件信息
    private static final int UPDATE_PATH = 2; //检查是否有patch更新
    private String mPatchFileDir;//patch要保存的文件夹
    private String mPatchFile;//path 文件保存路径
    private BasePath mBasePathInfo;//服务器 path信息


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }
    private void init() {
        mPatchFileDir = getExternalCacheDir().getAbsolutePath() + "/tpatch/";
        try {
            File patchFile = new File(mPatchFileDir);
            if (!patchFile.exists()) {
                patchFile.mkdir();//文件夹不存在创建
            }
        } catch (Exception e) {
            e.printStackTrace();
            stopSelf();//无法正常创建文件，则终止服务
        }
    }
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_PATH://向服务器检查是否有新的文件
                    checkPatchInfo();
                    break;
                case DOWNLOAD_PATH://下载 patch
                    downloadPatch();
                    break;
            }
        }
    };

    private void downloadPatch() {
        mPatchFile=mPatchFileDir.concat(String.valueOf(System.currentTimeMillis())).concat(FILE_END);
        RequestCenter.downloadFile(mBasePathInfo.getData().getDownloadUrl(),mPatchFileDir,new DisposeDownLoadListener(){

            @Override
            public void onProgeress(int progrss) {

            }

            @Override
            public void onSuccess(Object responseObj) {
                TinkerManager.loadPath(mPatchFileDir);
            }

            @Override
            public void onFailure(Object reasonObj) {
                stopSelf();
            }
        });
    }


    private void checkPatchInfo() {
        RequestCenter.requestPatchUpdataInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mBasePathInfo= (BasePath) responseObj;
                mHandler.sendEmptyMessage(DOWNLOAD_PATH);
            }

            @Override
            public void onFailure(Object reasonObj) {
                stopSelf();
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //检查是否有patch更新
        mHandler.sendEmptyMessage(UPDATE_PATH);
        return START_NOT_STICKY; //被系统回收不在创建
    }
}
